package erfgame.core.world.terrain.file;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;


import erfgame.core.Pair;
import erfgame.core.Point3D;
import erfgame.core.world.terrain.TerrainUpdate;
import erfgame.core.world.terrain.TerrainUpdateGroup;

public class TerrainUpdateSerializer {
	
	public static final TerrainUpdateGroup deserializeGroup( InputStream ins ) 
		throws IOException, ClassNotFoundException {
		DataInputStream dis = new DataInputStream(ins);
		int size = dis.readInt();
		List<Pair<Point3D, TerrainUpdate>> updates = new ArrayList<Pair<Point3D, TerrainUpdate>>(size);
		for( int i=0; i<size; i++ ) {
			int x = dis.readInt();
			int y = dis.readInt();
			int z = dis.readInt();
			Point3D position = new Point3D( x, y, z );
			TerrainUpdate update = deserialize( dis );
			updates.add( new Pair<Point3D, TerrainUpdate>(position, update) );
		}
		return new TerrainUpdateGroup( updates );
	}
	
	public static final void serializeGroup( TerrainUpdateGroup updateGroup, OutputStream outs ) 
		throws IOException {
		DataOutputStream dos = new DataOutputStream(outs);
		List<Pair<Point3D, TerrainUpdate>> updates = updateGroup.getTerrainUpdates();
		dos.writeInt( updates.size() );
		for( int i=0; i<updates.size(); i++ ) {
			Pair<Point3D, TerrainUpdate> pair = updates.get( i );
			Point3D position = pair.getFirst();
			TerrainUpdate update = pair.getSecond();
			dos.writeInt(position.x);
			dos.writeInt(position.y);
			dos.writeInt(position.z);
			serialize( update, dos );
		}
	}
	
	public static final TerrainUpdate deserialize( InputStream ins ) 
		throws IOException, ClassNotFoundException {
		ObjectInputStream oins = new ObjectInputStream(ins);
		return (TerrainUpdate)oins.readObject();
	}
	
	public static final void serialize( TerrainUpdate update, OutputStream outs ) 
		throws IOException {
		ObjectOutputStream oouts = new ObjectOutputStream(outs);
		oouts.writeObject(update);
	}
}
